package com.example.mtblog.tool;

import com.example.mtblog.common.Result;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.DownloadUrl;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;


@Component
public class FileUploadUtils {


    //设置AK和SK
    public static final String ACCESS_KEY = "zZ1QWBw_oTTBTi47bp7t2FqznyAq8xLf3smH3WgU";
    public static final String SECRET_KEY = "XWRRrGefhSdZXWaCBIlvBNFsjMHfZu6fwLK-h7OL";
    // 要上传的空间名（存储空间）
    public static final String bucketname = "mtblogoss";
    //外链域名
    public static final String domain = "s3dx4tnfo.hn-bkt.clouddn.com";

    private static final boolean useHttps = false;


    // 构建密钥
    public static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);


    public static Result<?> uploadImageToQiniu(MultipartFile multipartFile, String filename){
        try {

            //1、获取文件上传的流
            byte[] fileBytes = multipartFile.getBytes();

            //Region.南(根据自己的对象空间的地址选
            Configuration cfg = new Configuration(Region.huanan());//这是七牛云相关配置类上传的东西协议配置需要经行修改

            UploadManager uploadManager = new UploadManager(cfg);

            String token = auth.uploadToken(bucketname);

            Response res = uploadManager.put(fileBytes,filename,token);

            String url = download(filename);

            return  Result.success(url);

        } catch (IOException e) {

            System.out.println("error "+ e);
            return Result.error(String.valueOf(e));

        }

    }


    public static String download(String filename) throws QiniuException {
        // imgName：下载资源在七牛云存储的名字
        DownloadUrl url = new DownloadUrl(domain, useHttps, filename);
        //设置过期时间
        long l = System.currentTimeMillis();
        //1小时，可以自定义链接过期时间
        long expireInSeconds = 10;
        long deadline = System.currentTimeMillis()+expireInSeconds;
        return url.buildURL(auth, deadline);
    }

}
